package com.study.web.controller;

import com.study.web.dao.ResumeDao;
import com.study.web.pojo.Resume;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author zhangfd
 * @Date 2020/3/12 23:04
 * @Version 1.0
 * @Describe：
 */
@Controller
@RequestMapping("/demo1")
public class Demo1Contrller {

    @Autowired
    private ResumeDao resumeDao;
   /* @RequestMapping("/test")
    public ModelAndView test1(String name){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date",new Date());
        modelAndView.setViewName("/WEB-INF/jsp/sucess.jsp");
        return modelAndView;
    }*/

    @RequestMapping("/test")
    public ModelAndView test2(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        List<Resume> goodlist = new ArrayList<>();
        goodlist = resumeDao.findAll();
        request.getSession().setAttribute("goodlist",goodlist);
        modelAndView.setViewName("/WEB-INF/jsp/list.jsp");
        return modelAndView;
    }

    @RequestMapping("/doEdit")
    public ModelAndView doEdit(HttpServletRequest request,String id){
        ModelAndView modelAndView = new ModelAndView();
        Optional<Resume>  optional = resumeDao.findById(Long.valueOf(id));
        Resume resume = optional.get();
        modelAndView.addObject("id",resume.getId());
        modelAndView.addObject("address",resume.getAddress());
        modelAndView.addObject("name",resume.getName());
        modelAndView.addObject("phone",resume.getPhone());
        modelAndView.setViewName("/WEB-INF/jsp/edit.jsp");
        return modelAndView;
    }

    @RequestMapping("/doDelete")
    public ModelAndView doDelete(HttpServletRequest request,String id){
        try{
            resumeDao.deleteById((Long.valueOf(id)));
        }catch (Exception e){

        }
        return test2(request);
    }

    @RequestMapping("/doUpdate")
    public ModelAndView doUpdate(HttpServletRequest request,String id,String name,String address,String phone){

        Resume resume = new Resume();
        if (null !=id ){
            resume.setId(Long.valueOf(id));
        }
        resume.setName(name);
        resume.setAddress(address);
        resume.setPhone(phone);
        try{
            resumeDao.saveAndFlush(resume);
        }catch (Exception e){

        }

        return test2(request);
    }

    @RequestMapping("/doCreate")
    public ModelAndView doCreate(HttpServletRequest request,String name,String address,String phone){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/WEB-INF/jsp/create.jsp");
        return modelAndView;
    }


}
